const Base = require('./base.js');
module.exports = class extends Base {

	async getTaoword(info, level) {
		const alimama = think.service("alimama");
		let goodsId = await alimama.goodsId(info);
		let result = await this.getTaowordByGoodsId(goodsId, level);
		return result;

	}

	async getTaowordByGoodsId(goodsId, level) {
		try {

			const alimama = think.service("alimama");
			console.log(goodsId)
			let result = "";
			if(!goodsId) {
				return result;
			}
			let goodsDetail = await alimama.getDetail(goodsId);

			if(!goodsDetail) {
				return result;
			}
			console.log(goodsDetail)
			result = await alimama.transferLink(goodsId);
			let taoword = await alimama.getTaoword({
				'url': result.coupon_click_url,
				'text': goodsDetail.title,
				'logo': goodsDetail.pict_url
			});
			console.log(taoword)
			//		let clickUrl = urls.parse(result.coupon_click_url,true);
			//		console.log(clickUrl)
			//		result.coupon = await alimama.getCoupon(clickUrl.query.e);
			//		console.log(result.coupon)
			result.coupon_amout = 0;
			if(result.coupon_info) {
				result.coupon_condition = (result.coupon_info).match(/\u6EE1[0-9]{1,5}\u5143/)[0].slice(1, -1);
				result.coupon_amout = (result.coupon_info).match(/\u51CF[0-9]{1,5}\u5143/)[0].slice(1, -1);
			}
			let orderBuyerRate = await think.model("sys_user_level").where({
				id: level || 1
			}).getField("rebate_ratio", true);
			let orderBuyerVipRate = await think.model("sys_user_level").where({
				id: 2
			}).getField("rebate_ratio", true);
			result.kouling = taoword.data.model;
			result.goods = goodsDetail;
			result.final_price = (goodsDetail.zk_final_price - result.coupon_amout).toFixed(2);
			result.commission = (result.final_price * result.max_commission_rate / 100 * orderBuyerRate).toFixed(2);
			result.vipcommission = (result.final_price * result.max_commission_rate / 100 * orderBuyerVipRate).toFixed(2);

			return result;
		} catch(e) {
			console.log(e);
		}
	}

	async getResult(userid, content) {
		try {

			const qrcodeid = await think.model("taoke/qrcode").where({
				user_id: userid
			}).getField("id", true);
			const level = await think.model("system/user").where({
				id: userid
			}).getField("level", true);
			let result = await this.getTaoword(content, level);
			console.log(result);
			if(think.isEmpty(result)) {
				return false;
			}

			let data = {
				"title": result.goods.title,
				"org_price": result.goods.zk_final_price,
				"price": result.final_price,
				"quan_price": result.coupon_amout,
				"goods_id": result.goods.num_iid,
				"commission": result.max_commission_rate,
				"pic": result.goods.pict_url,
				"tao_word": result.kouling,
				"user_id": userid,
				"create_time": new Date().valueOf(),
				"source": 1
			}

			await this.add(data);
			data.qrcodeid = qrcodeid;
			data.commission = result.commission;

			return data;
		} catch(e) {
			console.log(e)
		}

	}

};